<?php

class Application_Model_CartProductMapper {
	
	protected $_dbTable;
	
	public function setDbTable($dbTable){
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}
	
	public function getDbTable(){
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_CartProduct');
		}
		return $this->_dbTable;
	}
	
	public function save(Application_Model_CartProduct $cartProduct){
		$data = array(
				'id_cart' => $cartProduct->getId_cart(),
				'id_product' => $cartProduct->getId_product(),
		);
	
		$this->getDbTable()->insert($data);
	}
	
	public function find($id, Application_Model_CartProduct $cartProduct){
		$result = $this->getDbTable()->find($id);
		if (0 == count($result)) {
			return;
		}
		$row = $result->current();
		$cartProduct->setId_cart($row->id_cart)
			->setId_product($row->id_product);
	}
	
	public function fetchAll() {
		$resultSet = $this->getDbTable()->fetchAll();
		$entries = array();
		foreach ($resultSet as $row) {
			$entry = new Application_Model_CartProduct();
			$entry->setId_cart($row->id_cart)
				->setId_product($row->id_product);
			$entries[] = $entry;
		}
		return $entries;
	}
	
	public function getProductIdsForCart($idCart){
		$resultSet = $this->getDbTable()->fetchAll(array(" id_cart = ?" => $idCart));
		
		$ids = array();
		foreach ($resultSet as $row) {
			$ids[] = $row->id_product;
		}
		return $ids;
	}
	
	public function deleteForCart($idCart){
		$where = $this->getDbTable()->getAdapter()->quoteInto('id_cart = ?', $idCart);
		return $this->getDbTable()->delete($where);
	}
}

